package org.hs.phd.odi.tracking.ui;

import java.awt.Color;

import java.awt.Polygon;

import org.hs.phd.common.framesource.FramePlayer;
import org.hs.phd.common.framesource.FrameProcessor;
import org.hs.phd.common.framesource.FrameSource;
import org.hs.phd.common.framesource.ImageSequenceFrame;
import org.hs.phd.odi.tracking.tracker.TrackerGroup;
import org.hs.phd.odi.tracking.tracker.comaniciu.ComaniciuTracker;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class TrackingPresenter {
	
	private final TrackingView view;
	private FramePlayer player;
	private TrackingModel model;
	private TrackerGroup trackerGroup;

	public TrackingPresenter(TrackingView view, FrameSource frameSource){
		this.view = view;
		this.model = new TrackingModel();
		this.trackerGroup = createTrackerGroup();
		this.player = frameSource.createPlayer(30, new FrameProcessor(){

			@Override
			public void process(ImageSequenceFrame frame) {
				onNextFrame(frame);
			}
			
		});
		
		
		view.setPresenter(this);
		
	}
	
	private TrackerGroup createTrackerGroup() {
		TrackerGroup trackerGroup = new TrackerGroup();
		trackerGroup.add( new ComaniciuTracker(), Color.RED );
		//trackerGroup.add( new OmniMeanshiftTracker(), Color.BLUE);
		return trackerGroup;
	}

	public void onStartup(){
		player.play();	
	}
	
	public void onClose(){
		player.stop();
		view.dispose();
		System.exit(0);
	}
	
	public void onStepNextFrame(){
		player.stepNext();
	}

	public void onStepPreviousFrame(){
		player.stepPrevious();
	}
	
	public void onReset(){
		player.reset();
	}

	public void onPause(){
		player.pause();	
	}

	public void onResume(){
		player.play();	
	}

	public void start() {
		view.show();
	}
	
	public void onTrackStarted(Polygon initialTrackShape, IplImage initialFrame){
		System.out.println("Track initialized at : " + initialTrackShape.getBounds() );
		trackerGroup.initTrackers(initialTrackShape, initialFrame);
	}
	
	public void onTrackDropped(){
		trackerGroup.dropTracks();
	}
	
	private void onNextFrame(ImageSequenceFrame frame) {
		
		System.out.println("Current frame : " + frame.getFrameNo() );
		
		trackerGroup.updateWithNextFrame(frame.getFrameImage());
		
		model.setImage(frame.getFrameImage());
		model.setTracks(trackerGroup.getTracks());
		view.updateModel(model);
	}

	public boolean isPaused() {
		return player.isPaused();
	}


}
